#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <wiringPi.h>

#include "voice_interface.h"
#include "socket_interface.h"
#include "smoke_interface.h"
#include "receive_interface.h"
#include "msg_queue.h"
#include "control.h"
#include "global.h"

int main(int argc, char *argv[])
{
    pthread_t thread_id;
    struct control *control_phead = NULL;
    struct control *pointer = NULL;
    ctrl_info_t *ctrl_info = NULL;
    ctrl_info = (ctrl_info_t *)malloc(sizeof(ctrl_info_t));    
    ctrl_info->ctrl_phead = NULL;
    ctrl_info->mqd = -1;

    int node_num = 0;

    if(-1 == wiringPiSetup())
    {
        return -1;
    }

    ctrl_info->mqd = msg_queue_create();

    if(ctrl_info->mqd == -1)
    {
        printf("%s|%s|%d,ctrl_info->mqd=%d\n",__FILE__,__func__,__LINE__,ctrl_info->mqd);
        return -1;
    }

    ctrl_info->ctrl_phead = add_voice_to_control_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_tcpsocket_to_control_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_smoke_to_control_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_receive_to_control_list(ctrl_info->ctrl_phead);
    //init
    pointer = ctrl_info->ctrl_phead;
    while(NULL != pointer)
    {
        if(NULL != pointer->init)
        {
            pointer->init();
        }
        pointer = pointer->next;
        node_num++; 
    }
    pthread_t *tid = malloc(sizeof(int) * node_num);
    //get
    pointer = ctrl_info->ctrl_phead; 
    for(int i = 0; i < node_num; i++)
    {
        if(NULL != pointer->get)
        {
            pthread_create(&tid[i], NULL,(void *)pointer->get, (void *)ctrl_info);   
        }
        pointer = pointer->next;
    }
    //join
    for(int i = 0; i < node_num; i++)
    {
        pthread_join(tid[i],NULL);
    }
    //final
    for(int i = 0; i < node_num; i++)
    {
        if(NULL != pointer->final)
            pointer->final();
        pointer = pointer->next;
    }
    msg_queue_fianl(ctrl_info->mqd);

    return 0;
}
